package cn.edu.sspu.www.web.interceptor;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.edu.sspu.www.contant.Constants;
import cn.edu.sspu.www.util.StringUtil;
import cn.edu.sspu.www.util.pattern.PatternMatcher;
import cn.edu.sspu.www.util.web.WebUtils;


/**
 * LoginInterceptor<br>
 * 自定义页面拦截器
 * 
 * @author warm
 * @version 2018年11月29日
 */
public class CustomInterceptor extends HandlerInterceptorAdapter {

	/** pathMatcher */
    protected PatternMatcher pathMatcher = new PatternMatcher();
    
	/**
	 * 不拦截的请求列表
	 */
	private List<String> excludeSuffixs;

	public List<String> getExcludeSuffixs() {
		return excludeSuffixs;
	}

	public void setExcludeSuffixs(List<String> excludeSuffixs) {
		this.excludeSuffixs = excludeSuffixs;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		// 1.公共参数
		request.setAttribute("ctx", request.getContextPath());
		
		// 2.请求过滤
		String requestURI = WebUtils.getPathWithinApplication(request);
		if (excludeSuffixs != null) {
			for (String suffix : excludeSuffixs) {
				if (pathsMatch(suffix, requestURI)) {
					System.out.println("skip : " + requestURI);
					return super.preHandle(request, response, handler);
				}
			}
		}

		System.out.println("Intercepter : " + requestURI);
		HttpSession session = request.getSession();
		if(null == session.getAttribute(Constants.SESSION_KEY)) {
			request.setAttribute("msg", "会话已过期，请重新登录");
			request.getRequestDispatcher("/unauth/login.action").forward(request, response);
			return false;
		}
		
		// 解析请求
		List<String> pathSplitList = StringUtil.toStrList(requestURI, "/");
		if (null != pathSplitList && pathSplitList.size() > 2) {
			request.setAttribute("prefix", pathSplitList.get(1));			
		}
		
		return super.preHandle(request, response, handler);
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		super.postHandle(request, response, handler, modelAndView);
	}
	
	/**
	 * match
	 * @param pattern
	 * @param path
	 * @return
	 */
	protected boolean pathsMatch(String pattern, String path) {
        return pathMatcher.matches(pattern, path);
    }
}
